package com.nari.ysphd.view;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Point;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import com.nari.ysphd.R;
import com.nari.ysphd.util.NotchScreenTool;


/**
 * Created by sunxunchao on 2019/1/25.
 */
public class DragView extends ViewGroup {

    private static final String TAG = "DragView";
    private ViewDragHelper viewDragHelper;
    private ViewGroup leftChildView, rightChildView;
    private int leftChildViewX, leftChildViewY, rightChildViewX, rightChildViewY;
    private boolean isOpen; //是否展开
    private boolean isNearRightView; //是否贴近右侧view
    private boolean canSlide = false; //能否滑动

    public static final int ZERO_SCREEN = 0x000;
    public static final int FOUR_SCREEN = 0x001;//四分屏
    public static final int EIGHT_SCREEN = 0x002;//八分屏
    public static final int TWELVE_SCREEN = 0x003;//十二分屏
    public static final int SIXTEEN_SCREEN = 0x004;//十六分屏

    private int screenType = FOUR_SCREEN;
    private int initType = FOUR_SCREEN;

    private int leftChildWidth;

    public DragView(Context context) {
        this(context, null);
    }

    public DragView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DragView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.DragView);
        isOpen = ta.getBoolean(R.styleable.DragView_isOpen, true);
        screenType = ta.getInt(R.styleable.DragView_screen_type, FOUR_SCREEN);
        isNearRightView = ta.getBoolean(R.styleable.DragView_isNearRightView, true);
        ta.recycle();

        initType = screenType;
        viewDragHelper = ViewDragHelper.create(this, 1.0f, callback);
    }

    public void setScreenType(int screenType) {
        this.screenType = screenType;
        this.initType = screenType;
    }

    public void setCanSlide(boolean canSlide) {
        this.canSlide = canSlide;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        int childCount = getChildCount();
        if (childCount != 2) {
            throw new IllegalStateException("Children num must equal 2");
        } else {
            leftChildView = (ViewGroup) getChildAt(0);
            rightChildView = (ViewGroup) getChildAt(1);
        }
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
        int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
        int measureHeight = MeasureSpec.getSize(heightMeasureSpec);
        // 计算出所有的childView的宽和高
        measureChildren(widthMeasureSpec, heightMeasureSpec);

        int displayWidth = Resources.getSystem().getDisplayMetrics().widthPixels;
        int displayHeight = Resources.getSystem().getDisplayMetrics().heightPixels;
        displayWidth = displayWidth - (NotchScreenTool.isNotch(getContext()) ? 2 * NotchScreenTool.getNotchHeight(getContext()): 0);
        Log.d(TAG, "onMeasure: w ==" + displayWidth + " h ==" + displayHeight);
//        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
//        Point point = new Point();
//        if (wm != null) {
//            wm.getDefaultDisplay().getRealSize(point);
//        }
//
//        int displayWidth = point.x;
//        int displayHeight = point.y;
//        Log.d(TAG, "全面屏实际大小：" + point.toString());


        leftChildWidth = displayWidth - (4 * screenType) * displayHeight / 9;

        if (isNearRightView) {
            int rChildWidth = leftChildView.getMeasuredWidth();
            int count = leftChildView.getChildCount();
            for (int i = 0; i < count; i++) {
                View child = leftChildView.getChildAt(i);
                int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(child.getMeasuredHeight(), MeasureSpec.EXACTLY);
                int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(leftChildWidth, MeasureSpec.AT_MOST);
                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
            }
        }


        int width = 0;
        int height = 0;

        int lChildHeight = leftChildView.getMeasuredHeight();
        int rChildHeight = rightChildView.getMeasuredHeight();
        int lChildWidth = leftChildView.getMeasuredWidth();
        int rChildWidth = rightChildView.getMeasuredWidth();

        MarginLayoutParams lParams = (MarginLayoutParams) leftChildView.getLayoutParams();
        MarginLayoutParams rParams = (MarginLayoutParams) rightChildView.getLayoutParams();
        height = Math.max((lChildHeight + lParams.topMargin + lParams.bottomMargin), (rChildHeight + rParams.topMargin + rParams.bottomMargin));
        width = rChildWidth + rParams.leftMargin + rParams.rightMargin;

        setMeasuredDimension((modeWidth == MeasureSpec.EXACTLY) ? measureWidth : width,
                (modeHeight == MeasureSpec.EXACTLY) ? measureHeight : height);
    }

    /**
     * viewgroup支持margin需要重写该方法
     *
     * @param attrs
     * @return
     */
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }


    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new MarginLayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        int lChildHeight = leftChildView.getMeasuredHeight();
        int rChildHeight = rightChildView.getMeasuredHeight();
        int lChildWidth = leftChildView.getMeasuredWidth();
        int rChildWidth = rightChildView.getMeasuredWidth();

        MarginLayoutParams lParams = (MarginLayoutParams) leftChildView.getLayoutParams();
        MarginLayoutParams rParams = (MarginLayoutParams) rightChildView.getLayoutParams();

        if (isNearRightView) {
            leftChildView.layout(lParams.leftMargin,
                    lParams.topMargin,
                    leftChildWidth,
                    lChildHeight + lParams.topMargin + lParams.bottomMargin);
        } else {
            leftChildView.layout(lParams.leftMargin,
                    lParams.topMargin,
                    lChildWidth + lParams.leftMargin + lParams.rightMargin,
                    lChildHeight + lParams.topMargin + lParams.bottomMargin);
        }
        if (isOpen) {
            rightChildView.layout(leftChildWidth + rParams.leftMargin,
                    rParams.topMargin,
                    rChildWidth * (4 + screenType) / 4 - rParams.rightMargin,
                    rChildHeight - rParams.bottomMargin);
        } else {
            rightChildView.layout(rParams.leftMargin,
                    rParams.topMargin,
                    lChildWidth + rChildWidth - rParams.rightMargin,
                    rChildHeight - rParams.bottomMargin);
        }

        leftChildViewX = leftChildView.getLeft();
        leftChildViewY = leftChildView.getTop();
        rightChildViewX = rightChildView.getLeft();
        rightChildViewY = rightChildView.getTop();
    }

    private ViewDragHelper.Callback callback = new ViewDragHelper.Callback() {
        @Override
        public boolean tryCaptureView(View view, int i) {
            Log.d(TAG, "tryCaptureView: " + i);
            return canSlide && view == rightChildView;
        }

        @Override
        public void onViewDragStateChanged(int state) {
            Log.d(TAG, "onViewDragStateChanged: " + state);
        }

        @Override
        public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
            Log.d(TAG, "onViewPositionChanged: left:" + left + " top:" + top + " dx:" + dx + " dy:" + dy);
        }

        @Override
        public int getViewHorizontalDragRange(View child) {
            return child.getMeasuredWidth();
        }

        @Override
        public int clampViewPositionHorizontal(View child, int left, int dx) {
            MarginLayoutParams lParams = (MarginLayoutParams) leftChildView.getLayoutParams();
            MarginLayoutParams rParams = (MarginLayoutParams) rightChildView.getLayoutParams();

            int paddingLeft = getPaddingLeft() + rParams.leftMargin;
            if (left < paddingLeft) {
                return paddingLeft;
            }
            int pos = leftChildWidth + rightChildView.getPaddingLeft() + rParams.leftMargin;
            if (left > pos) {
                return pos;
            }
            return left;
        }

        @Override
        public int clampViewPositionVertical(View child, int top, int dy) {
            MarginLayoutParams rParams = (MarginLayoutParams) rightChildView.getLayoutParams();
            return rParams.topMargin;
        }

        @Override
        public void onViewCaptured(View capturedChild, int activePointerId) {
        }

        @Override
        public void onViewReleased(View releasedChild, float xvel, float yvel) {
            if (releasedChild == rightChildView) {
                if (releasedChild.getLeft() < rightChildViewX / 2) {
                    viewDragHelper.settleCapturedViewAt(0, 0);
//                    screenType = ZERO_SCREEN;
                } else {
                    viewDragHelper.settleCapturedViewAt(rightChildViewX, rightChildViewY);
//                    screenType = initType;
                }
                invalidate();
            }

            Log.d(TAG, "onViewReleased: ===> xvel:" + xvel + " yvel:" + yvel);
        }
    };


    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return viewDragHelper.shouldInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        viewDragHelper.processTouchEvent(event);
        return true;
    }

    @Override
    public void computeScroll() {
        if (viewDragHelper != null && viewDragHelper.continueSettling(true)) {
            invalidate();
        }
    }
}
